package com.cloudcentral.util;

import com.cloudcentral.exception.FailureException;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;

/**
 * Create by Administrator
 * 2023/11/3 15:36
 */
public class VerifyUtils {
  public static boolean captcha(RedissonClient redissonClient, String captchaId, String captcha) throws FailureException {
    if (StringUtils.isBlank(captchaId) || StringUtils.isBlank(captcha)) throw new FailureException("缺少图形验证码");
    else {
      RBucket<String> bucket = redissonClient.getBucket(captchaId);
      String value = bucket.getAndDelete();
      if (StringUtils.isBlank(value)) throw new FailureException("图形验证码已过期");
      else if (!StringUtils.equalsIgnoreCase(value, captcha)) throw new FailureException("图形验证码错误");
      else return true;
    }
  }

  public static boolean code(RedissonClient redissonClient, String phone, String code) throws FailureException {
    if (StringUtils.isBlank(phone)) throw new FailureException("缺少手机号");
    else if (StringUtils.isBlank(code)) throw new FailureException("缺少短信验证码");
    else {
      RBucket<String> bucket = redissonClient.getBucket(phone);
      String value = bucket.getAndDelete();
      if (StringUtils.isBlank(value)) throw new FailureException("短信验证码已过期");
      else if (!StringUtils.equalsIgnoreCase(value, code)) throw new FailureException("短信验证码错误");
      else return true;
    }
  }
}
